import {FmtFuncDef} from './fmt.d'
import {MfLite} from './dropdownlist.d'
import _ from 'lodash'
import dayjs from 'dayjs'

const dtFmtFullWithMSec = function (dt: Date | string): string {
  if(!dt) {
    return ''
  }
  const dj = dayjs(dt)
  return dj.isValid() ? dj.format('YYYY-MM-DD HH:mm:ss.SSS') : ''
}

// Date格式化方法:完整时间日期(不带秒)
const dtFmtFullNoSec = function (dt: Date | string): string {
  if(!dt) {
    return ''
  }
  const dj = dayjs(dt)
  return dj.isValid() ? dj.format('YYYY-MM-DD HH:mm') : ''
}

// 格式化方法:只有日期 2016-11-04
const dtFmtDateOnly = function (dt: Date | string): string {
  if(!dt) {
    return ''
  }
  const dj = dayjs(dt)
  return dj.isValid() ? dj.format('YYYY-MM-DD') : ''
}

// 格式化方法:只有时间 13:52:11
const dtFmtTimeOnly = function (dt: Date | string): string {
  if(!dt) {
    return ''
  }
  const dj = dayjs(dt)
  return dj.isValid() ? dj.format('HH:mm:ss') : ''
}

// 格式化方法:只有时间(不带秒) 13:52
const dtFmtTimeOnlyNoSec = function (dt: Date | string): string {
  if(!dt) {
    return ''
  }
  const dj = dayjs(dt)
  return dj.isValid() ? dj.format('HH:mm') : ''
}

// 格式化方法:完整时间日期 2016-11-04 13:52:11
const dtFmtFull = function (dt: Date | string): string {
  if(!dt) {
    return ''
  }
  const dj = dayjs(dt)
  return dj.isValid() ? dj.format('YYYY-MM-DD HH:mm:ss') : ''
}

// 格式化方法: HH:mm 将Date转为
const dtFmtHourMinute = function(dt:Date | string):string{
  if(!dt){
    return ''
  }
  let dtVal:Date|string
  if(typeof(dt)==='string'){
    dt = dt.trim()
    if(/^\d{2}:\d{2}(:\d{2})?$/.test(dt)){
      dtVal = '2000-01-01 ' + dt
    }
    else{
      return ''
    }
  }
  else{
    dtVal = dt
  }
  const dj = dayjs(dtVal)
  return dj.isValid() ? dj.format('HH:mm') : ''
}

// 反格式化，把字符串转为Date
const dtFromString = function (dtStr: string): Date {
  return dayjs(dtStr).toDate()
}

// 文件大小,展示KB,MB等单位
const fileSizeDisp = function (fileSize: number): string {
  const sizes = ['B', 'KB', 'MB', 'GB']
  let order = 0
  while (fileSize > 1024 && ++order < sizes.length) {
    fileSize /= 1024
  }
  return fileSize.toFixed(2) + sizes[order]
}

const _currencyData: Record<string, string> = {}

// (需要prepare) 格式化币别: 142 => 人民币(CNY)
const currency = function (value: string): string {
  return _currencyData[value] ?? value
}

// 准备币别格式化
const prepareCurrencyFmt = function (separation?: boolean) {
  $f.lst.getCodeForDropdown('Currency').then(items => {
    for (const item of items) {
      if (separation) {
        _currencyData[item.codeValue] = item.codeValue+'|'+item.codeName1+'|'+ item.codeName2
      }
      else {
        _currencyData[item.codeValue] = item.codeName2 + '(' + item.codeName1 + ')'
      }
    }
  }).catch(() => {
    //ignore
  })
}

const _uomData: Record<string, string> = {}

// (需要prepare) 格式化计量单位: 007 => 007-个
const uom = function (value: string): string {
  return _uomData[value] ?? value
}

// 准备计量单位格式化
const prepareUomFmt = function (separation?: boolean) {
  $f.lst.getCodeForDropdown('UOM').then(items => {
    for (const item of items) {
      if (separation) {
        _uomData[item.codeValue] = item.codeValue + '|' + item.codeName1
      }
      else {
        _uomData[item.codeValue] = item.codeValue + '(' + item.codeName1 + ')'
      }
    }
  }).catch(() => {
    //ignore
  })
}

const _lcTypeData: Record<string, string> = {}

// (需要prepare) 格式化支付方式: 2 => 电汇
const lcType = function (value: string): string {
  return _lcTypeData[value] ?? value
}

// 准备支付方式格式化
const prepareLcTypeFmt = function () {
  $f.lst.getCodeForDropdown('LcType').then(items => {
    for (const item of items) {
      _lcTypeData[item.codeValue] = item.codeName1
    }
  }).catch(() => {
    //ignore
  })
}

const _countryData: Record<string, string> = {}

// (需要prepare) 格式化国别: 142 => 中国(CNY)
const country = function (value: string): string {
  return _countryData[value] ?? value
}

// 准备国别格式化
const prepareCountryFmt = function (separation?: boolean) {
  $f.lst.getCodeForDropdown('Country').then(items => {
    for (const item of items) {
      if (separation) {
        _countryData[item.codeValue] = item.codeValue + '|' + item.codeName1 + '|' + item.codeName2
      } else {
        _countryData[item.codeValue] = item.codeName2 + '(' + item.codeName1 + ')'
      }
    }
  }).catch(() => {
    //ignore
  })
}

const _mfData: Record<number, string> = {}

// (需要prepare) 格式化客商: mfId => mfAbbrName
const mfAbbrName = function (value: number): string {
  return _mfData[value] ?? value
}

// 准备客商格式化
const prepareMfFmt = function () {
  // 这里是获取全部客商的信息，对类型不作区分
  $f.lst.getMfSimpleList({}).then(result => {
    for (const mf of result.mfLiteList) {
      _mfData[mf.mfId] = mf.abbrName
    }
  }).catch(() => {
    //ignore
  })
}

// 为下拉列表准备的
const mfLiteDisp = function (mfLite:MfLite):string {
  if(mfLite.extraInfo){
    return mfLite.abbrName + ' - ' + mfLite.extraInfo
  }
  return mfLite.abbrName
}

const _companyData: Record<string, string> = {}

// (需要prepare) 格式化公司: companyId => companyAbbrName
const companyAbbrName = function (value: string): string {
  return _companyData[value] ?? value
}

// 准备公司格式化
const prepareCompanyFmt = function () {
  $f.lst.getCompanySimpleList().then(companyList => {
    for (const company of companyList) {
      _companyData[company.companyId] = company.abbrName
    }
  }).catch(() => {
    //ignore
  })
}

// 格式化用户显示 p, pn => 'pn(p)'
const userDisp = function (p: string, pn: string | null): string {
  if (pn) {
    return pn + '(' + p + ')'
  } else {
    return p
  }
}

// 内部bool类型格式化方法
function boolDispInternal(value: boolean | string | null | undefined, disp: string[]) {
  if (typeof value === 'boolean') {
    return value ? disp[0] : disp[1]
  } else if (typeof value === 'string') {
    switch (value.toLowerCase()) {
      case 'true':
        return disp[0]
      case 'false':
        return disp[1]
    }
  }
  return disp[2]
}

// true/false => 是/否
const yesNoDisp = function (value: boolean | string | null | undefined): string {
  return boolDispInternal(value, ['是', '否', ''])
}

// true/false => 有效/无效
const validInvalidDisp = function (value: boolean | string | null | undefined): string {
  return boolDispInternal(value, ['有效', '无效', ''])
}

//true/false => 启用/停用
const enabledDisabledDisp = function (value: boolean | string | null | undefined): string {
  return boolDispInternal(value, ['启用', '停用', ''])
}

//用户内部标志位格式化
const userInternalTagsDisp = function (value: string | null | undefined): string {
  if ($f.globalCfg.userInternalTagsData) {
    const match = _.find($f.globalCfg.userInternalTagsData, i => i.value == value)
    if (match) {
      return match.label
    }
  }
  return value ? value : ''
}

// 格式化最长显示字符
const ellipsisContent = function (value: string, length: number): string {
  if (value) {
    return value.length > length ? value.substring(0, length - 3) + '...' : value
  } else {
    return ''
  }
}

export default {
  dtFmtFullWithMSec,
  dtFmtFullNoSec,
  dtFmtDateOnly,
  dtFmtTimeOnly,
  dtFmtTimeOnlyNoSec,
  dtFmtFull,
  dtFmtHourMinute,
  dtFromString,
  fileSizeDisp,
  currency,
  prepareCurrencyFmt,
  uom,
  prepareUomFmt,
  lcType,
  prepareLcTypeFmt,
  country,
  prepareCountryFmt,
  mfAbbrName,
  prepareMfFmt,
  mfLiteDisp,
  companyAbbrName,
  prepareCompanyFmt,
  userDisp,
  yesNoDisp,
  validInvalidDisp,
  enabledDisabledDisp,
  userInternalTagsDisp,
  ellipsisContent
} as FmtFuncDef
